package demo.model;

import org.owasp.validator.html.*;
import org.springframework.util.StringUtils;

import java.net.URL;

/**
 * @author ：jiangHaoTing
 * @date ：2025/4/15 16:17
 */
public class NoteStringUtils {
    private static Policy policy;

    static {
        try {
            URL url = NoteStringUtils.class.getClassLoader().getResource("conf/antisamy-ebay.xml");
            policy = Policy.getInstance(url);
        } catch (Exception e) {
        }
    }

    private NoteStringUtils() {

    }

    public static String xssFilter(String str) {
        if (StringUtils.isEmpty(str)) {
            return "";
        }
        try {
            AntiSamy as = new AntiSamy();
            CleanResults cr = as.scan(str, policy);
            str = cr.getCleanHTML();
        } catch (ScanException scanException) {
        } catch (PolicyException policyException) {
        }
        return str;
    }

    /**
     * 替换UTF8MB4字符。
     *
     * @param str
     * @return
     */
    public static String replaceUtf8mb4(String str) {
        str =  xssFilter(str);
        if (StringUtils.isEmpty(str)) {
            return "";
        }
        int length = str.length();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            char ch = str.charAt(i);
            if (Character.isHighSurrogate(ch)) {
                if ((i + 1) >= length) {
                    continue;
                }
                sb.append("&#");
                sb.append(Character.toCodePoint(ch, str.charAt(i + 1)));
                sb.append(';');
                i++;
            } else {
                sb.append(ch);
            }
        }
        return sb.toString();
    }
}
